package com.huashi.dealer.modular.business.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.commonEntity.GoodsImage;
import com.huashi.dealer.commonEntity.GoodsSku;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.commonEntity.Category;
import com.huashi.dealer.core.util.BizAssertUtil;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.goods.bo.GoodsAddBo;
import com.huashi.dealer.modular.business.goods.mapper.GoodsMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsSkuMapper;
import com.huashi.dealer.modular.business.goods.mapper.CategoryMapper;
import com.huashi.dealer.modular.business.goods.service.GoodsService;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.goods.param.StoreGoodsListParam;
import com.huashi.dealer.modular.business.goods.service.StoreGoodsService;
import com.huashi.dealer.modular.business.goods.vo.StoreGoodsListVo;
import com.huashi.dealer.modular.business.goods.vo.StoreGoodsDetailVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Store端商品服务实现类
 *
 * @author 谭陈强
 * @since 2025-08-07
 */
@Slf4j
@Service
public class StoreGoodsServiceImpl implements StoreGoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsImageMapper goodsImageMapper;

    @Resource
    private GoodsSkuMapper goodsSkuMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private UploadFileMapper uploadFileMapper;
    @Autowired
    private GoodsService goodsService;

    @Override
    public Page<StoreGoodsListVo> getGoodsList(StoreGoodsListParam param, Page<Goods> page) {
        // 构建查询条件
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        
        // 基础条件：未删除的商品，且是商品类型（非赠品）
        queryWrapper.eq(Goods::getIsDelete, 0)
                   .eq(Goods::getIsType, 10);
        
        // 分类筛选
        if (param.getCategoryId() != null) {
            queryWrapper.eq(Goods::getCategoryId, param.getCategoryId());
        }
        
        // 状态筛选
        if (param.getStatus() != null) {
            queryWrapper.eq(Goods::getGoodsStatus, param.getStatus());
        }
        
        // 搜索关键词
        if (StringUtils.hasText(param.getSearch())) {
            queryWrapper.like(Goods::getGoodsName, param.getSearch());
        }
        if (param.getIsNewproduct() != null){
            queryWrapper.eq(Goods::getIsNewproduct, param.getIsNewproduct());
        }
        if (param.getIsHotsellingitem() != null){
            queryWrapper.eq(Goods::getIsHotsellingitem, param.getIsHotsellingitem());
        }
        // 排序：按排序值升序，创建时间降序
        queryWrapper.orderByAsc(Goods::getGoodsSort)
                   .orderByDesc(Goods::getCreateTime);
        
        // 分页查询
        Page<Goods> goodsPage = goodsMapper.selectPage(page, queryWrapper);
        
        // 转换为VO
        Page<StoreGoodsListVo> resultPage = new Page<>();
        BeanUtils.copyProperties(goodsPage, resultPage);
        
        List<StoreGoodsListVo> voList = goodsPage.getRecords().stream()
                .map(this::convertToStoreGoodsListVo)
                .collect(Collectors.toList());

        resultPage.setRecords(voList);
        return resultPage;
    }

    @Override
    public StoreGoodsDetailVo getGoodsDetail(Long goodsId) {
        // 查询商品基本信息
        Goods goods = goodsMapper.selectById(goodsId);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 转换为VO
        StoreGoodsDetailVo vo = new StoreGoodsDetailVo();
        BeanUtils.copyProperties(goods, vo);
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(goods.getCreateTime()));
        vo.setUpdateTime(TimeUtil.changeToLocalDateTime(goods.getUpdateTime()));
        // 查询商品图片
        LambdaQueryWrapper<GoodsImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(GoodsImage::getGoodsId, goodsId)
                   .orderByAsc(GoodsImage::getId);
        List<GoodsImage> images = goodsImageMapper.selectList(imageWrapper);
        
        List<StoreGoodsDetailVo.GoodsImageVo> imageVos = images.stream()
                .map(image -> {
                    StoreGoodsDetailVo.GoodsImageVo imageVo = new StoreGoodsDetailVo.GoodsImageVo();
                    imageVo.setImageId(image.getImageId());

                    List<String> fileUrlByGoodsId = goodsImageMapper.getFileUrlByGoodsId(image.getGoodsId());
                    if(CollUtil.isNotEmpty(fileUrlByGoodsId)) {
                        if(fileUrlByGoodsId.size() == 1){
                            imageVo.setFilePath(fileUrlByGoodsId.get(0));
                        }else {
                            imageVo.setFilePath(CollUtil.join(fileUrlByGoodsId, ","));
                        }
                    }
                    return imageVo;
                })
                .collect(Collectors.toList());
        vo.setImage(imageVos);
        
        // 查询商品规格
        LambdaQueryWrapper<GoodsSku> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(GoodsSku::getGoodsId, goodsId)
                 .orderByAsc(GoodsSku::getGoodsSkuId);
        List<GoodsSku> skus = goodsSkuMapper.selectList(skuWrapper);
        
        List<StoreGoodsDetailVo.GoodsSkuVo> skuVos = skus.stream()
                .map(sku -> {
                    StoreGoodsDetailVo.GoodsSkuVo skuVo = new StoreGoodsDetailVo.GoodsSkuVo();
                    BeanUtils.copyProperties(sku, skuVo);
                    return skuVo;
                })
                .collect(Collectors.toList());
        vo.setSku(skuVos);
        
        // 查询商品分类
        if (goods.getCategoryId() != null) {
            Category category = categoryMapper.selectById(goods.getCategoryId());
            if (category != null) {
                StoreGoodsDetailVo.CategoryVo categoryVo = new StoreGoodsDetailVo.CategoryVo();
                categoryVo.setCategoryId(category.getCategoryId());
                categoryVo.setName(category.getName());
                vo.setCategory(categoryVo);
            }
        }
        
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsStatus(Long goodsId, Boolean state) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getGoodsId, goodsId)
                    .set(Goods::getGoodsStatus, state ? 10 : 20);
        
        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("商品不存在或更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsNewStatus(Long goodsId, Boolean state) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getGoodsId, goodsId)
                    .set(Goods::getIsNewproduct, state ? 10 : 20);
        
        int result = goodsMapper.update(updateWrapper);
        if (result == 0) {
            throw new RuntimeException("商品不存在或更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsHotStatus(Long goodsId, Boolean state) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getGoodsId, goodsId)
                    .set(Goods::getIsHotsellingitem, state ? 10 : 20);
        
        int result = goodsMapper.update(updateWrapper);
        if (result == 0) {
            throw new RuntimeException("商品不存在或更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsSort(Long goodsId, Integer goodsSort) {
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getGoodsId, goodsId)
                    .set(Goods::getGoodsSort, goodsSort);
        
        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("商品不存在或更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGoods(Long goodsId) {
        // 软删除
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Goods::getGoodsId, goodsId)
                    .set(Goods::getIsDelete, 1);

        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("商品不存在或删除失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpStatus(List<Long> goodsIds) {
        if (goodsIds == null || goodsIds.isEmpty()) {
            throw new RuntimeException("商品ID列表不能为空");
        }
        
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Goods::getGoodsId, goodsIds)
                    .set(Goods::getGoodsStatus, 10);
        
        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("批量上架失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDownStatus(List<Long> goodsIds) {
        if (goodsIds == null || goodsIds.isEmpty()) {
            throw new RuntimeException("商品ID列表不能为空");
        }
        
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Goods::getGoodsId, goodsIds)
                    .set(Goods::getGoodsStatus, 20);
        
        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("批量下架失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> goodsIds) {
        if (goodsIds == null || goodsIds.isEmpty()) {
            throw new RuntimeException("商品ID列表不能为空");
        }
        
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Goods::getGoodsId, goodsIds)
                    .set(Goods::getIsDelete, 1);
        
        int result = goodsMapper.update(null, updateWrapper);
        if (result == 0) {
            throw new RuntimeException("批量删除失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsAddBo bo) {
        Goods goods = bo.getGoods();
        GoodsSku goodsSku = bo.getGoodsSku();
        goods.setSpecType(10);
        goods.setCreateTime(System.currentTimeMillis()/1000);
        goodsSku.setCreateTime(System.currentTimeMillis()/1000);
        goodsSku.setGoodsSales(goods.getSalesInitial());
        goodsService.save(goods);
        goodsSku.setGoodsId(goods.getGoodsId());
        goodsSku.setImageId(bo.getImage().get(0));
        goodsSkuMapper.insert(goodsSku);
        List<Long> images = bo.getImage();
        if(!images.isEmpty()) {
            images.stream().forEach(image -> {
                GoodsImage goodsImage = new GoodsImage();
                goodsImage.setCreateTime(System.currentTimeMillis() / 1000);
                goodsImage.setGoodsId(goods.getGoodsId());
                goodsImage.setImageId(image);
                goodsImageMapper.insert(goodsImage);
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsAddBo bo) {
        Goods goods = bo.getGoods();
        BizAssertUtil.notNull(goods.getGoodsId(), 10001, "商品id不能为空");
        GoodsSku goodsSku = bo.getGoodsSku();

        if(bo.getImage() != null&& !bo.getImage().isEmpty() ){
            updateGoodImage(bo.getImage(),goods.getGoodsId());
        }
        if (goods != null && goods.getGoodsId() != null) {
            goodsMapper.updateById(goods);
        }
        GoodsSku goodsSku1 = goodsSkuMapper.selectOne(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goods.getGoodsId()));
        BizAssertUtil.notNull(goodsSku1.getGoodsSkuId(), 10001, "该商品未查询到SkuId");
        goodsSku.setGoodsSkuId(goodsSku1.getGoodsSkuId());
        goodsSkuMapper.updateById(goodsSku);
    }

    @Override
    public void updateInfo(Goods good) {
        goodsMapper.updateById(good);
    }

    private void updateGoodImage(List<Long> image, Long goodsId) {
        // 1. 查询数据库中当前商品的所有图片
        LambdaQueryWrapper<GoodsImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsImage::getGoodsId, goodsId);
        List<GoodsImage> existingImages = goodsImageMapper.selectList(queryWrapper);

        // 2. 提取现有图片的imageId列表
        List<Long> existingImageIds = existingImages.stream()
                .map(GoodsImage::getImageId)
                .collect(Collectors.toList());

        // 3. 找出需要新增的图片（在新列表中但不在现有列表中）
        List<Long> imagesToAdd = image.stream()
                .filter(imageId -> !existingImageIds.contains(imageId))
                .collect(Collectors.toList());

        // 4. 找出需要删除的图片（在现有列表中但不在新列表中）
        List<Long> imagesToDelete = existingImageIds.stream()
                .filter(imageId -> !image.contains(imageId))
                .collect(Collectors.toList());

        // 5. 删除不再需要的图片
        if (!imagesToDelete.isEmpty()) {
            LambdaQueryWrapper<GoodsImage> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(GoodsImage::getGoodsId, goodsId)
                    .in(GoodsImage::getImageId, imagesToDelete);
            goodsImageMapper.delete(deleteWrapper);
        }

        // 6. 新增新的图片
        if (!imagesToAdd.isEmpty()) {
            for (Long imageId : imagesToAdd) {
                GoodsImage goodsImage = new GoodsImage();
                goodsImage.setGoodsId(goodsId);
                goodsImage.setImageId(imageId);
                goodsImage.setCreateTime(System.currentTimeMillis() / 1000);
                goodsImageMapper.insert(goodsImage);
            }
        }
    }

    /**
     * 转换为StoreGoodsListVo
     */
    private StoreGoodsListVo convertToStoreGoodsListVo(Goods goods) {
        StoreGoodsListVo vo = new StoreGoodsListVo();
        BeanUtils.copyProperties(goods, vo);
        // 设置创建时间（Goods 为 epoch 秒，需要转为 LocalDateTime）
        if (goods.getCreateTime() != null) {
            vo.setCreateTime(LocalDateTime.ofEpochSecond(goods.getCreateTime(), 0, ZoneOffset.ofHours(8)));
        }
        
        // 设置商品状态
        StoreGoodsListVo.GoodsStatusVo statusVo = new StoreGoodsListVo.GoodsStatusVo();
        statusVo.setValue(goods.getGoodsStatus());
        statusVo.setText(goods.getGoodsStatus() == 10 ? "上架" : "下架");
        vo.setGoodsStatus(statusVo);
        
        // 设置新品状态
        StoreGoodsListVo.GoodsStatusVo newStatusVo = new StoreGoodsListVo.GoodsStatusVo();
        newStatusVo.setValue(goods.getIsNewproduct());
        newStatusVo.setText(goods.getIsNewproduct() == 10 ? "是" : "否");
        vo.setIsNewproduct(newStatusVo);
        
        // 设置爆款状态
        StoreGoodsListVo.GoodsStatusVo hotStatusVo = new StoreGoodsListVo.GoodsStatusVo();
        hotStatusVo.setValue(goods.getIsHotsellingitem());
        hotStatusVo.setText(goods.getIsHotsellingitem() == 10 ? "是" : "否");
        vo.setIsHotsellingitem(hotStatusVo);
        
        // 查询商品图片
        LambdaQueryWrapper<GoodsImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(GoodsImage::getGoodsId, goods.getGoodsId())
                   .orderByAsc(GoodsImage::getId)
                   .last("LIMIT 1");
        GoodsImage image = goodsImageMapper.selectOne(imageWrapper);
        
        if (image != null) {
            StoreGoodsListVo.GoodsImageVo imageVo = new StoreGoodsListVo.GoodsImageVo();
            imageVo.setImageId(image.getImageId());
            // 查询上传文件，获取可访问的图片地址
            UploadFile uploadFile = uploadFileMapper.selectById(image.getImageId());
            if (uploadFile != null) {
                String url = uploadFile.getFileUrl();
                imageVo.setFilePath(url != null && !url.isEmpty() ? url : uploadFile.getFileName());
            }
            vo.setImage(List.of(imageVo));
        }
        
        // 查询商品分类
        if (goods.getCategoryId() != null) {
            Category category = categoryMapper.selectById(goods.getCategoryId());
            if (category != null) {
                StoreGoodsListVo.CategoryVo categoryVo = new StoreGoodsListVo.CategoryVo();
                categoryVo.setCategoryId(category.getCategoryId());
                categoryVo.setName(category.getName());
                vo.setCategory(categoryVo);
            }
        }
        
        return vo;
    }
}
